package com.bsoft.gol.hcs.clinical.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.*;
import com.bsoft.gol.hcs.clinical.bean.req.inspectionreq.Visit;
import com.bsoft.gol.hcs.clinical.bean.response.*;
import com.bsoft.gol.hcs.clinical.bean.vo.*;
import com.bsoft.gol.hcs.clinical.dao.*;
import com.bsoft.gol.hcs.clinical.service.TreatmentApplicationService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.BeanUtils;
import ctd.util.annotation.RpcService;
import hcn.base.*;
import hcn.util.BaseResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import pcn.prescribe.DisposalExpenseDetail;
import pcn.prescribe.DisposalExpenseRecord;
import com.bsoft.gol.hcs.specialist.dao.TreatmentRecordDAO;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import com.bsoft.gol.hcs.utils.DateUtil;
import org.atag.util.http.KdHttpClientUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 治疗申请单
 */
@SsdevService("treatmentApplicationService")
public class TreatmentApplicationServiceImpl implements TreatmentApplicationService {

    private static Logger log = LoggerFactory.getLogger(TreatmentApplicationServiceImpl.class);


    @Autowired
    private DisposalExpenseRecordDAO disposalExpenseRecordDAO;
    @Autowired
    private DisposalExpenseDetailDAO disposalExpenseDetailDAO;

    @Autowired
    private TreatmentApplicationRecordDAO treatmentApplicationRecordDAO;

    @Autowired
    private TreatmentApplicationRecordDetailDAO treatmentApplicationRecordDetailDAO;

    @Autowired
    private TreatmentAcupointsDAO treatmentAcupointsDAO;

    @Autowired
    private TreatmentAcupointsDetailEntityDAO treatmentAcupointsDetailEntityDAO;

    @Autowired
    private TreatmentMeasuresDAO treatmentMeasuresDAO;
    @Autowired
    private TreatmentEvaluationRecodeDAO treatmentEvaluationRecodeDAO;
    @Autowired
    private TreatmentRecordDAO treatmentRecordDAO;
    /**
     * 治疗项目类别获取
     * @param request
     * @return
     */
    @Override
    @RpcService
    public List<TreatmentItemTypeListResp> findTreatmentItemTypeList(TreatmentApplicationRequest request) {

        String url=Constants.COMMON_PROXY_URL+Constants.TREATMENT_ITEM_TYPE_LIST;
        String rest = KdHttpClientUtil.doPostJSONRequest(url, JSONObject.toJSONString(request));
        BaseResponse baseResponse = JSON.parseObject(rest, BaseResponse.class);
        List<TreatmentItemTypeListResp> data=new ArrayList<>();
        if (baseResponse.getCode()==200){
            data = JSON.parseArray(baseResponse.getData().toString(), TreatmentItemTypeListResp.class);
        }
        return data;
    }

    /**
     *治疗项目获取
     */
    @Override
    @RpcService
    public List<TreatmentItemTypeList> getTreatmentItem(GetTreatmentItemRequest request) {
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url=Constants.COMMON_PROXY_URL+Constants.GET_TREATMENT_ITEM;
        JSONObject rest = KdHttpClientUtil.doPostJSONRequest(url, jsonObject);
        BaseResponse baseResponse = JSON.parseObject(rest.toString(), BaseResponse.class);
        List<TreatmentItemTypeList> data=new ArrayList<>();
        if (baseResponse.getCode()==200) {
            data = JSON.parseArray(baseResponse.getData().toString(), TreatmentItemTypeList.class);
        }
        return data;
    }

    /**
     * 治疗信息获取
     * @return
     */
    @Override
    @RpcService
    public List<TreatmentCodeVo> getTreatmentItemList() {
        return treatmentRecordDAO.queryTreatmentCodeList();
    }

    /**
     * 穴位信息获取
     */
    @Override
    public List<MeridianList> getMeridianList(TreatmentApplicationRequest request){
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url=Constants.COMMON_PROXY_URL+Constants.GET_MERIDIAN_lIST;
        JSONObject rest = KdHttpClientUtil.doPostJSONRequest(url, jsonObject);
        BaseResponse baseResponse = JSON.parseObject(rest.toString(), BaseResponse.class);
        List<MeridianList> data=new ArrayList<>();
        if (baseResponse.getCode()==200){
            data = JSON.parseArray(baseResponse.getData().toString(), MeridianList.class);
        }
        return data;
    }

    /**
     * 治疗组套信息获取
     */
    @Override
    public List<TreatmentSetList> getTreatmentSet(TreatmentApplicationRequest request){
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url=Constants.COMMON_PROXY_URL+Constants.GET_TREATMENT_SET;
        JSONObject rest = KdHttpClientUtil.doPostJSONRequest(url, jsonObject);
        BaseResponse baseResponse = JSON.parseObject(rest.toString(), BaseResponse.class);
        List<TreatmentSetList> data=new ArrayList<>();
        if (baseResponse.getCode()==200){
            data = JSON.parseArray(baseResponse.getData().toString(), TreatmentSetList.class);
        }
        return data;
    }

    /**
     * 治疗组套明细信息获取
     */
    @Override
    public List<TreatmentSetDetailList> getTreatmentSetDetail(TreatmentSetDetailRequest request){
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url=Constants.COMMON_PROXY_URL+Constants.GET_TREATMENT_SET_DETAIL;
        JSONObject rest = KdHttpClientUtil.doPostJSONRequest(url, jsonObject);
        BaseResponse baseResponse = JSON.parseObject(rest.toString(), BaseResponse.class);
        List<TreatmentSetDetailList> data=new ArrayList<>();
        if (baseResponse.getCode()==200){
            data = JSON.parseArray(baseResponse.getData().toString(), TreatmentSetDetailList.class);
        }
        if (CommonUtils.isNotEmpty(data)){
            for (TreatmentSetDetailList treatmentSetList:data) {
                GetTreatmentItemRequest getTreatmentItemRequest = new GetTreatmentItemRequest();
                getTreatmentItemRequest.setVisitOrganization(request.getVisitOrganization());
                getTreatmentItemRequest.setTreatmentItemTypeCode(treatmentSetList.getTreatmentItemTypeCode());
               treatmentSetList.setTypeLists(getTreatmentItem(getTreatmentItemRequest));
            }
        }
        return data;
    }

    /**
     * 提交单据
     */
    @Override
    public void submitTreatment(SubmitTreatmentRequest request) throws ControllerException {

        if (CommonUtils.isEmpty(request.getTreatmentIds())){
            throw new ControllerException("申请单id集合不能为空！");
        }
        AddTreatmentRequest submit = new AddTreatmentRequest();
        List<ExmRequestList> list=new ArrayList<>();
        for (String treatmentId:request.getTreatmentIds()) {
            ExmRequestList exmRequestList = new ExmRequestList();
            TreatmentApplicationRecord record = treatmentApplicationRecordDAO.getByTreatmentId(treatmentId);
            TreatmentApplicationRecordDetail recordDetail = treatmentApplicationRecordDetailDAO.getByTreatmentId(treatmentId);
            List<TreatmentAcupointsDetailEntity> acupointsDetailEntities = treatmentAcupointsDetailEntityDAO.findByTreatmentId(treatmentId);
            List<TreatmentMeasuresEntity> treatmentMeasuresEntities = treatmentMeasuresDAO.findByTreatmentId(treatmentId);
            List<TreatmentEvaluationRecodeEntity> evaluationRecodeEntity = treatmentEvaluationRecodeDAO.findByTreatmentId(treatmentId);
            BeanUtils.copy(recordDetail,exmRequestList);
            BeanUtils.copy(record,submit);
            exmRequestList.setAcupointLists(acupointsDetailEntities);
            exmRequestList.setTreatmentItemExplainLists(treatmentMeasuresEntities);
            exmRequestList.setEvaluationProjectLists(evaluationRecodeEntity);
            exmRequestList.setOnlineRequestId(treatmentId);
            list.add(exmRequestList);
        }
        submit.setExmRequestLists(list);
        PatientVo patient = new PatientVo();
        BeanUtils.copy(submit,patient);
        patient.setVisitOrganization(submit.getOrganizationId());
        submit.setPatient(patient);
        Visit visit = new Visit();
        BeanUtils.copy(submit,visit);
        visit.setVisitOrganization(submit.getOrganizationId());
        submit.setVisit(visit);

        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(submit));
        String url=Constants.COMMON_PROXY_URL+Constants.ADD_TREATMENT_REQUEST;
        JSONObject rest = KdHttpClientUtil.doPostJSONRequest(url, jsonObject);
        BaseResponse baseResponse = JSON.parseObject(rest.toString(), BaseResponse.class);
        List<ExmRequestList> data=new ArrayList<>();
        if (baseResponse.getCode()==200){
            data = JSON.parseArray(baseResponse.getData().toString(), ExmRequestList.class);
        }

        log.info("submitTreatment his返回： "+data);
        for (ExmRequestList exmRequestList :data) {
            if (StringUtils.isEmpty(exmRequestList.getOnlineRequestId())){
                continue;
            }
            disposalExpenseRecordDAO.updateByItemId((byte)1,exmRequestList.getRequestId(),exmRequestList.getFeeNo(),exmRequestList.getOnlineRequestId());
            treatmentApplicationRecordDAO.updateApplicationById(exmRequestList.getRequestId(),exmRequestList.getOnlineRequestId());
            TreatmentApplicationRecord record = treatmentApplicationRecordDAO.getByTreatmentId(exmRequestList.getOnlineRequestId());
            try {
                log.info("发送IM检查消息 入参：  "+JSONObject.toJSON(record).toString());
                Client.rpcInvoke("hco.consultImEasemobService", "sendTreatmentMessage", JSONObject.toJSON(record).toString());
                log.info("发送IM检查消息------结束");
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 治疗申请单信息新增
     */
    @Override
    public void addTreatmentRequest(AddTreatmentRequest request) throws ControllerException {

        if (CommonUtils.isEmpty(request)||CommonUtils.isEmpty(request.getExmRequestLists())){
            throw  new ControllerException("申请单内容不能为空！");
        }
        if (CommonUtils.isEmpty(request)||CommonUtils.isEmpty(request.getOrganizationId())){
            throw  new ControllerException("机构code为空！");
        }

        DisposalExpenseRecord disposalExpenseRecord = new DisposalExpenseRecord();
        BeanUtils.copy(request,disposalExpenseRecord);
        TreatmentApplicationRecord treatmentApplicationRecord = new TreatmentApplicationRecord();
        BeanUtils.copy(request,treatmentApplicationRecord);
        for (int i = 0; i <request.getExmRequestLists().size() ; i++) {

            treatmentApplicationRecord.setTreatmentId(UUID.randomUUID().toString().replace("-",""));
            treatmentApplicationRecord.setInHospitalRecordCode(request.getVisitId());
            treatmentApplicationRecord.setApplicationNo(request.getExmRequestLists().get(i).getRequestId());
            treatmentApplicationRecord.setReqTime(new Date());
            treatmentApplicationRecord.setDisableTime(DateUtil.getNextDay());
            treatmentApplicationRecord.setPatientName(request.getName());
            treatmentApplicationRecordDAO.save(treatmentApplicationRecord);

            TreatmentApplicationRecordDetail detail = new TreatmentApplicationRecordDetail();
            detail.setDetailId(UUID.randomUUID().toString().replace("-",""));
            detail.setTreatmentId(treatmentApplicationRecord.getTreatmentId());
            BeanUtils.copy(request.getExmRequestLists().get(i),detail);
            detail.setTreatmentItemCost(detail.getTreatmentItemPrice().multiply(detail.getTreatTimesNumber().multiply(detail.getTreatmentCourse())));
            treatmentApplicationRecordDetailDAO.save(detail);

            TreatmentMeasuresEntity treatmentMeasuresEntity = new TreatmentMeasuresEntity();
            if (CommonUtils.isNotEmpty(request.getExmRequestLists().get(i).getTreatmentItemExplainLists())){
                BeanUtils.copy(request.getExmRequestLists().get(i).getTreatmentItemExplainLists().get(0),treatmentMeasuresEntity);
            }
            treatmentMeasuresEntity.setTreatmentMeasuresId(UUID.randomUUID().toString().replace("-",""));
            treatmentMeasuresEntity.setTreatmentId(treatmentApplicationRecord.getTreatmentId());
            treatmentMeasuresDAO.save(treatmentMeasuresEntity);

            TreatmentEvaluationRecodeEntity treatmentEvaluationRecodeEntity = new TreatmentEvaluationRecodeEntity();
            if (CommonUtils.isNotEmpty(request.getExmRequestLists().get(i).getEvaluationProjectLists())){
                BeanUtils.copy(request.getExmRequestLists().get(i).getEvaluationProjectLists().get(0),treatmentEvaluationRecodeEntity);
            }
            treatmentEvaluationRecodeEntity.setTreatmentEvaluationRecodeId(UUID.randomUUID().toString().replace("-",""));
            treatmentEvaluationRecodeEntity.setTreatmentId(treatmentApplicationRecord.getTreatmentId());
            treatmentEvaluationRecodeDAO.save(treatmentEvaluationRecodeEntity);

            disposalExpenseRecord.setExpenseId(UUID.randomUUID().toString().replace("-",""));
         //   disposalExpenseRecord.setExpenseIdSource(data.get(i).getFeeNo());
         //   disposalExpenseRecord.setApplicationNo(request.getExmRequestLists().get(i).getRequestId());
            disposalExpenseRecord.setApplyDoctorId(request.getDoctorId());
            disposalExpenseRecord.setApplyDoctorName(request.getDoctorName());
            disposalExpenseRecord.setState((byte)0);
            disposalExpenseRecord.setBillCategoryCode("7");
            //业务类型 1 互联网诊疗   2 核酸开单',
            disposalExpenseRecord.setBusinessType("1");
            disposalExpenseRecord.setBusinessId(treatmentApplicationRecord.getTreatmentId());
            disposalExpenseRecord.setBillCategoryCode("7");
            disposalExpenseRecord.setItemId(treatmentApplicationRecord.getTreatmentId());
            disposalExpenseRecord.setItemName(request.getExmRequestLists().get(i).getTreatmentItemName());
            disposalExpenseRecord.setExpirationDate(DateUtil.getNextDay());
            disposalExpenseRecord.setPayStatus("0");
            disposalExpenseRecord.setPersonName(request.getName());
            disposalExpenseRecord.setCardNumber(request.getIdCard());
            disposalExpenseRecord.setCardType(request.getIdCardType());
            disposalExpenseRecord.setApplyDoctorId(request.getDoctorId());
            disposalExpenseRecord.setApplyDoctorName(request.getDoctorName());
            disposalExpenseRecord.setApplyDepartmentId(request.getDepartmentId());
            disposalExpenseRecord.setApplyDepartmentName(request.getDepartmentName());
            disposalExpenseRecordDAO.save(disposalExpenseRecord);

            DisposalExpenseDetail disposalExpenseDetail = new DisposalExpenseDetail();
            disposalExpenseDetail.setExpenseDetailId(UUID.randomUUID().toString().replace("-",""));
            disposalExpenseDetail.setExpenseId(disposalExpenseRecord.getExpenseId());
            disposalExpenseDetail.setItemId(request.getExmRequestLists().get(i).getTreatmentItemCode());
            disposalExpenseDetail.setItemName(request.getExmRequestLists().get(i).getTreatmentItemName());
            disposalExpenseDetail.setNumber(request.getExmRequestLists().get(i).getTreatTimesNumber().multiply(request.getExmRequestLists().get(i).getTreatmentCourse()));
            disposalExpenseDetail.setPrice(request.getExmRequestLists().get(i).getTreatmentItemPrice());
            disposalExpenseDetail.setUnit(request.getExmRequestLists().get(i).getTreatmentItemUnit());
            disposalExpenseDetail.setAmount(disposalExpenseDetail.getNumber().multiply(disposalExpenseDetail.getPrice()));
            disposalExpenseDetailDAO.save(disposalExpenseDetail);

            TreatmentAcupoints treatmentAcupoints = new TreatmentAcupoints();
            treatmentAcupoints.setTreatmentAcupointsId(UUID.randomUUID().toString().replace("-",""));
            treatmentAcupoints.setTreatmentId(treatmentApplicationRecord.getTreatmentId());
            treatmentAcupoints.setApplicationNo(request.getExmRequestLists().get(i).getRequestId());
            treatmentAcupointsDAO.save(treatmentAcupoints);
            if (CommonUtils.isEmpty(request.getExmRequestLists().get(i).getAcupointLists())){
                continue;
            }
            for (TreatmentAcupointsDetailEntity acupointsDetailEntity:request.getExmRequestLists().get(i).getAcupointLists()) {

                acupointsDetailEntity.setTreatmentAcupointsDetailId(UUID.randomUUID().toString().replace("-",""));
                acupointsDetailEntity.setTreatmentAcupointsId(treatmentAcupoints.getTreatmentAcupointsId());
                treatmentAcupointsDetailEntityDAO.save(acupointsDetailEntity);

            }
        }
    }


    /**
     * 治疗申请单信息查询
     */
    @Override
    public QueryTreatmentResp queryTreatmentRequest(QueryTreatmentRequest request) {
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url=Constants.COMMON_PROXY_URL+Constants.QUERY_TREATMENT_REQUEST;
        JSONObject rest = KdHttpClientUtil.doPostJSONRequest(url, jsonObject);
        BaseResponse baseResponse = JSON.parseObject(rest.toString(), BaseResponse.class);
        QueryTreatmentResp resp = new QueryTreatmentResp();
        if ("200".equals(baseResponse.getCode())){
            resp = JSON.parseObject(baseResponse.getData().toString(), QueryTreatmentResp.class);
        }
        return resp;
    }

    /**
     * 治疗申请单  报告信息查询
     * @param request
     * @return
     */
    @Override
    public BaseResponse<QueryTreatmentReportResp> queryTreatmentReport(GetTreatmentApplicationRequest request) throws ControllerException {

        if (StringUtils.isEmpty(request.getTreatmentId())){
            throw new ControllerException("申请单id 不能为空");
        }
        TreatmentApplicationRecord record = treatmentApplicationRecordDAO.getByTreatmentId(request.getTreatmentId());
        QueryTreatmentRequest queryTreatmentRequest=new QueryTreatmentRequest();
        BeanUtils.copy(record,queryTreatmentRequest);
        queryTreatmentRequest.setPageNo(1);
        queryTreatmentRequest.setPageSize(1);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(queryTreatmentRequest));
        String url=Constants.COMMON_PROXY_URL+Constants.QUERY_TREATMENT_REPORT;
        JSONObject rest = KdHttpClientUtil.doPostJSONRequest(url, jsonObject);
        return JSON.parseObject(rest.toString(), BaseResponse.class);
    }


    /**
     * 治疗申请单列表
     */
    @Override
    public List<FindTreatmentApplicationListResp> findTreatmentApplicationList(FindTreatmentApplicationListRequest request) throws ControllerException {
        if (StringUtils.isEmpty(request.getPatientId())){
            throw new ControllerException("患者id不能为空！");
        }
        if (StringUtils.isEmpty(request.getConsultId())){
            throw new ControllerException("当前问诊id不能为空！");
        }
        List<FindTreatmentApplicationListResp> treatmentApplicationList = treatmentApplicationRecordDAO.findTreatmentApplicationList(request);
        return treatmentApplicationList;
    }

    /**
     * 回撤申请单
     */
    @Override
    public BaseResponse returnTreatmentRequest(ReturnTreatmentRequest request) throws ControllerException {

        if (StringUtils.isEmpty(request.getRequestId())){
            throw  new ControllerException("申请单号不能为空！");
        }
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url=Constants.COMMON_PROXY_URL+Constants.RETURN_TREATREATMENT_REQUEST;
        JSONObject rest = KdHttpClientUtil.doPostJSONRequest(url, jsonObject);
        BaseResponse baseResponse = JSON.parseObject(rest.toString(), BaseResponse.class);
        log.info(" returnTreatmentRequest 出参： "+ baseResponse);
        if (baseResponse.getCode()==200){
            disposalExpenseRecordDAO.updateStateAndApplicationNoByItemId((byte)0,"",request.getTreatmentId());
        }
        return baseResponse;
    }

    /**
     * 查看申请单的详细信息
     */
    @Override
    public TreatmentApplicationResp getTreatmentApplication(GetTreatmentApplicationRequest request) throws ControllerException {

        if (StringUtils.isEmpty(request.getTreatmentId())){
            throw new ControllerException("申请单id不能为空");
        }
        TreatmentApplicationRecord record = treatmentApplicationRecordDAO.getByTreatmentId(request.getTreatmentId());
        TreatmentApplicationRecordDetail recordDetail = treatmentApplicationRecordDetailDAO.getByTreatmentId(request.getTreatmentId());
        List<TreatmentAcupointsDetailEntity> acupointsDetailEntities = treatmentAcupointsDetailEntityDAO.findByTreatmentId(request.getTreatmentId());
        TreatmentApplicationResp resp = new TreatmentApplicationResp();
        resp.setAcupoints(acupointsDetailEntities);
        resp.setDetail(recordDetail);
        resp.setRecord(record);
        return resp;
    }


    /**
     * 编辑申请单
     */
    @Override
    public void updateTreatment(TreatmentApplicationResp request) {

        if (CommonUtils.isNotEmpty(request.getDetail())&&StringUtils.isNotEmpty(request.getDetail().getDetailId())){
            BigDecimal price = request.getDetail().getTreatmentItemPrice();
            BigDecimal course = request.getDetail().getTreatmentCourse();
            BigDecimal number = request.getDetail().getTreatTimesNumber();
            request.getDetail().setTreatmentItemCost(price.multiply(course.multiply(number)));
            treatmentApplicationRecordDetailDAO.update(request.getDetail());
        }
        if (CommonUtils.isNotEmpty(request.getRecord())&&StringUtils.isNotEmpty(request.getRecord().getTreatmentId())){
            DisposalExpenseRecord disposalExpenseRecord = disposalExpenseRecordDAO.getDisposalExpenseRecordByItemId(request.getRecord().getTreatmentId());
            List<DisposalExpenseDetail> disposalExpenseDetails = disposalExpenseDetailDAO.queryDisposalExpenseDetail(disposalExpenseRecord.getExpenseId());
            if (CommonUtils.isNotEmpty(disposalExpenseDetails)){
                DisposalExpenseDetail disposalExpenseDetail = disposalExpenseDetails.get(0);
                disposalExpenseDetail.setNumber(request.getDetail().getTreatTimesNumber().multiply(request.getDetail().getTreatmentCourse()));
                disposalExpenseDetail.setAmount(disposalExpenseDetail.getNumber().multiply(disposalExpenseDetail.getPrice()));
                disposalExpenseDetailDAO.update(disposalExpenseDetail);
            }
        }
        if (CommonUtils.isEmpty(request.getAcupoints())){
            return;
        }
        TreatmentAcupoints acupoints = treatmentAcupointsDAO.getByTreatmentId(request.getRecord().getTreatmentId());
        if (CommonUtils.isEmpty(acupoints)){
            acupoints = new TreatmentAcupoints();
            acupoints.setTreatmentId(request.getRecord().getTreatmentId());
            acupoints.setTreatmentAcupointsId(UUID.randomUUID().toString().replace("-",""));
            treatmentAcupointsDAO.save(acupoints);
        }else{
            treatmentAcupointsDetailEntityDAO.deleteByAcupointsId(acupoints.getTreatmentAcupointsId());
        }
        for (TreatmentAcupointsDetailEntity entity:request.getAcupoints()) {

            entity.setTreatmentAcupointsDetailId(UUID.randomUUID().toString().replace("-",""));
            entity.setTreatmentAcupointsId(acupoints.getTreatmentAcupointsId());
            treatmentAcupointsDetailEntityDAO.save(entity);
        }
    }
    /**
     * 删除
     */
    @Override
    public void delete(GetTreatmentApplicationRequest request) throws ControllerException {

        if (StringUtils.isEmpty(request.getTreatmentId())){
            throw new ControllerException("申请单id不能为空");
        }

        treatmentApplicationRecordDAO.deleteByTreatmentId(request.getTreatmentId());
        treatmentApplicationRecordDetailDAO.deleteByTreatmentId(request.getTreatmentId());

        TreatmentAcupoints acupoints = treatmentAcupointsDAO.getByTreatmentId(request.getTreatmentId());
        if (CommonUtils.isNotEmpty(acupoints)&&StringUtils.isNotEmpty(acupoints.getTreatmentAcupointsId())){
            treatmentAcupointsDetailEntityDAO.deleteByAcupointsId(acupoints.getTreatmentAcupointsId());
        }
        treatmentAcupointsDAO.deleteByTreatmentId(request.getTreatmentId());

        DisposalExpenseRecord record = disposalExpenseRecordDAO.getDisposalExpenseRecordByItemId(request.getTreatmentId());
        if (CommonUtils.isNotEmpty(record)&&StringUtils.isNotEmpty(record.getExpenseId())){
            disposalExpenseDetailDAO.deleteDisposalExpenseDetail(record.getExpenseId());
        }
        disposalExpenseRecordDAO.deleteDisposalExpenseRecordByItemId(request.getTreatmentId());
    }

    /**
     * 获取各种状态的总数
     * @param request
     * @return
     * @throws ControllerException
     */
    @Override
    public TreatmentCountResp count(GetTreatmentApplicationRequest request) throws ControllerException {
        if (StringUtils.isEmpty(request.getPatientId())){
            throw new ControllerException("患者id不能为空");
        }
        TreatmentCountResp resp = new TreatmentCountResp();
        resp.setNotSubmitCount(treatmentApplicationRecordDAO.countByStatus("0", request.getPatientId()));
        resp.setSubmitCount(treatmentApplicationRecordDAO.countByStatus("1", request.getPatientId()));
        resp.setAppointmentCount(treatmentApplicationRecordDAO.countByStatus("2", request.getPatientId()));
        resp.setExecuteCount(treatmentApplicationRecordDAO.countByStatus("3", request.getPatientId()));
        return resp;
    }

}
